package cn.ddcollection.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.ddcollection.model.AccessKey;
import cn.ddcollection.model.DataCollector;
import cn.ddcollection.model.Ec2Instance;
import cn.ddcollection.model.Region;

import cn.ddcollection.service.DataCollectorService;

import cn.ddcollection.service.Ec2Service;
import cn.ddcollection.service.UserService;
import cn.ddcollection.utils.AWSCredentialsUtil;
import cn.ddcollection.utils.PropertiesOperatator;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.RegionUtils;
import com.amazonaws.services.ec2.AmazonEC2Client;

/**
 * 
 * @ClassName: Ec2Controller
 * @Description: ec2的控制器
 * @author: 大鹤
 * @date: 2016年2月24日 下午9:37:48
 */
@Controller
@RequestMapping("/ec2")
public class Ec2Controller {
	@Resource(name = "ec2Service")
	private Ec2Service ec2Service;
	@Resource(name = "userService")
	private UserService userService;
	@Resource(name = "dataCollectorService")
	private DataCollectorService dataCollectorService;
	private AmazonEC2Client ec2;

	/**
	 * 
	 * @Title: toEc2List
	 * @Description: 跳转到ec2list.jsp
	 * @return
	 * @return: String
	 */
	@RequestMapping("toec2list")
	public String toEc2List() {
		return "ec2/ec2list";
	}

	/**
	 * 
	 * @Title: getUserKeyList
	 * @Description: 获取用户名和awsAccessKey、awsSecretAccessKey
	 * @return
	 * @throws IOException
	 * @return: List<AccessKey>
	 */
	@RequestMapping("getuserkeylist")
	public @ResponseBody List<AccessKey> getUserKeyList() throws IOException {
		return PropertiesOperatator
				.getUserName(this.getClass().getClassLoader().getResource("").getPath() + "conf/userkey.properties");
	}

	/**
	 * 
	 * @Title: getRegionList
	 * @Description: TODO获取region的名字和value，并传递给easyui-combobox
	 * @return
	 * @throws IOException
	 * @return: List<Region>
	 */
	@RequestMapping("getregionlist")
	public @ResponseBody List<Region> getRegionList() throws IOException {
		return PropertiesOperatator
				.getRegionName(this.getClass().getClassLoader().getResource("").getPath() + "conf/region.properties");
	}

	public String listEc2Instances(HttpServletRequest request) throws Exception {
		return "ec2/ec2list";
	}

	@RequestMapping("tocreateec2")
	public String Createec2() {
		return "ec2/ec2create";
	}
	
	@RequestMapping("toswitchec2")
	public String switchec2() {
		return "ec2/ec2switch";
	}

	@RequestMapping("launchinstance")
	public String launchInstance(@RequestParam("uploadShell") CommonsMultipartFile file,HttpServletRequest request) {
		String key = request.getParameter("userkey");
		BasicAWSCredentials credentials = AWSCredentialsUtil.getBasicAWSCredentials(key.split(" ")[0],
				key.split(" ")[1]);
		String username = request.getParameter("username");
		String region = request.getParameter("region");
		String description = request.getParameter("description");
		ec2 = new AmazonEC2Client(credentials);
		ec2.setEndpoint("https://" + region + ".amazonaws.com");
		ec2.setRegion(RegionUtils.getRegion(region.trim()));
		Ec2Instance ec2instance = new Ec2Instance();
		// String userData, String imageId, String username,
		// String region, String striam, String name
		
		ec2instance.setEc2name(request.getParameter("ec2name"));
		ec2instance.setDcname(request.getParameter("dataCollector"));
		ec2instance.setDescription(description);
		
		ec2instance.setImageid(PropertiesOperatator
				.GetValueByKey(this.getClass().getClassLoader().getResource("").getPath() + "conf/regionami.properties",
						region)
				.trim());
		String iam = PropertiesOperatator.GetValueByKey(
				this.getClass().getClassLoader().getResource("").getPath() + "conf/iamuser.properties", username);
		ec2instance.setIam(iam);
///////////////////userdata
		if(file!=null){
			File destFile = new File("F:/学习资料/测试文件/myShell.txt");
			try {
				if(!destFile.exists()){
					destFile.createNewFile();
				}
				FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
			} catch (IOException e) {
				e.printStackTrace();
			}// 复制临时文件到指定目录下
			ec2instance.setUserdata(ec2Service.getUserdataFromFile(destFile.getAbsolutePath()));
		}
		ec2instance.setRegion(region);
		ec2instance.setUsername(username);
		ec2Service.launchInstance(ec2, ec2instance, username);
		System.out.println("success");
		//insert ec2Instance
		ec2instance.setUsername(description);
		ec2Service.insertEc2(ec2instance);
		System.out.println("success----------------------------");
		
		return null;
	}
	
	/**
	 * 
	 * @Title: getRegionList
	 * @Description: TODO获取region的名字和value，并传递给easyui-combobox
	 * @return
	 * @throws IOException
	 * @return: List<Region>
	 */
	@RequestMapping("getDataCollectorlist")
	public @ResponseBody List<DataCollector> getDataCollectorList() throws IOException {
		return dataCollectorService.findDataCollectorAll();
	}

}
